using System;
using System.Linq;

namespace SilenthinkCommon.Extension
{
    public class SilenthinkIdentity
    {
        public int Id { get; set; }
        public string NickName { get; set; }
        public string[] Role { get; set; }
        public int[] Permission { get; set; }
        public string AuthType { get; set; }
        public SilenthinkIdentity(int id, string nickName, string role, string permission)
        {
            Id = id;
            NickName = nickName;
            Role = string.IsNullOrEmpty(role) ? new string[0] : role.Split(',');
            Permission = StringToInt(permission);
        }

        public SilenthinkIdentity(): this(0, null, null, null)
        {

        }

        private static int[] StringToInt(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return new int[0];
            }
            var array = str.Split(',');
            var arrayLen = array.Length;
            var intArray = new int[arrayLen];
            for (var i = 0; i < arrayLen; i++)
            {
                intArray[i] = Convert.ToInt32(array[i]);
            }
            return intArray;
        }
    }

    public static class SilenthinkIdentityExtension
    {
        public static bool HasPermission(this SilenthinkIdentity identity, int permission)
        {
            return identity.Permission.Contains(permission);
        }
    }
}